<?php
class Request{
    protected $request;
    protected $defaultIndex;
    public $method;
    public $protocol;
    public $protocolVersion;
    public $path;
    public $query;
    public $host;
    public $accept;
    public $acceptEncoding;
    public $acceptLanguage;
    public $connection;
    public $userAgent;
    public $referer;
    public $cacheControl;
    public $cookie;
    public $_GET;
    public $_POST;
    public $_REQUEST;
    public $_SERVER;
    public $headerMatchArr = array(
        'Accept'=>'accept',
        'Accept-Encoding'=>'acceptEncoding',
        'Accept-Language'=>'acceptLanguage',
        'Connection'=>'connection',
        'Host'=>'host',
        'User-Agent'=>'userAgent',
        'Referer'=>'referer',
        'Cache-Control'=>'cacheControl',
        'Cookie'=>'cookie'
    );
    public $vars = array();
    public $template;

    public function __construct($req){
        $this->request = $req;
        $this->parse();
    }

    protected function parse(){
        $req = explode(PHP_EOL,$this->request);
        //协议及请求数据
        $top = array_shift($req);
        $bottom = array_pop($req);
        //默认请求
        $top = $top=='GET / HTTP/1.1'?'GET /Index/index HTTP/1.1':$top;
        $top = explode(' ',$top);
        $protocols = explode('/',@$top[2]);
        //解析url
        $url = parse_url(@$top[1]);
        $this->method = $top[0];
        $this->path = $url['path'];
        $this->query = @$url['query'];
        $this->protocol = $protocols[0];
        $this->protocolVersion = @$protocols[1];
        if($bottom){
            //解析post或get数据
            $params = explode('&',$bottom);
            $tmp_method = '_'.$this->method;
            $tmp_request = '_REQUEST';
            foreach($params as $v){
                $p = explode('=',$v);
                $this->{$tmp_method}[$p[0]] = $p[1];
                $this->{$tmp_request}[$p[0]] = $p[1];
            }
        }
        //解析辅助头数据
        $obj = $this;
        array_walk($req,function($v)use($req,$obj){
            if($v){
                $item = explode(': ',$v);
                array_key_exists($item[0],$obj->headerMatchArr) and $obj->{$obj->headerMatchArr[$item[0]]} = $item[1];
            }
        });
    }
}